<?php
/**
 * @filesource modules/category/controllers/CategoryController.php
 * @author Dao Quang Duc
 */ 
Class Category_MasterController extends Clu_Controller_Action_Master
{
	public $m; //model

	public function init()
	{
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		$this->mArticle = new article_Model_Service();
		$this->m = new category_Model_Category();
		parent::init();
	}
 	  	
	public function moderateCategoryAction()
	{
       $sess = new Zend_Session_Namespace(CLU_NS);
        //check user rights
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
                
		$this->viewParams['successMessage'] = '';
		$this->viewParams['errorMessage'] = '';
		if ($moduleCategoryName = $this->_request->getParam("module_category"))
	   	{
	   		$operation = $this->_request->getParam("operation");
	   		if ($operation == 'new') 
        		$sql = sprintf("CREATE TABLE `%s` (
                          `id` int(8) NOT NULL auto_increment,
                          `article_id` int(8) NULL default 0,
                          `name` varchar(256) collate utf8_unicode_ci NOT NULL,
                          `description` text collate utf8_unicode_ci NOT NULL,
                          `title` varchar(512) collate utf8_unicode_ci default NULL,
                          `tree_path` varchar(512) collate utf8_unicode_ci NOT NULL,
                          `weight` tinyint(4) NOT NULL default '100',
                          `allow_multiselect` tinyint(1) NOT NULL,
                          PRIMARY KEY  (`id`)
                        	) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
    
    					CREATE TABLE `%s` (
      					`id` int(8) NOT NULL,
      					`pid` int(8) NOT NULL,
                          PRIMARY KEY  (`id`,`pid`)
                        ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
                        ", 'categories_' . $moduleCategoryName, 'category_relations_' . $moduleCategoryName );
			else if ($operation == 'delete')
				$sql = sprintf(" DROP TABLE `%s`; DROP TABLE `%s`;", 'categories_' . $moduleCategoryName, 'category_relations_' . $moduleCategoryName );
    		try 
    		{
    			$this->db->query($sql);
    			$this->viewParams['successMessage'] = $operation . __(" <i>categories_$moduleCategoryName </i> and <i>category_relations_$moduleCategoryName </i> successful");
    		}
			catch (Exception $e)    
			{
    			$this->viewParams['errorMessage'] = __("Something wrong when ") .$operation."ing the table" . $e->getMessage();
			}
	   	}		
	   	$this->viewParams['module_category'] = $moduleCategoryName;
	}
	
	public function newAction()
	{	
		$sess = new Zend_Session_Namespace(CLU_NS);
		//check user rights
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
//        $this->viewParams['form']->populate($a->toArray());
		if(!$type = $this->_request->getParam('type'))
      	{
      		$this->viewParams['errorMessage'] = t(505);
      		$this->presenceIdentifier = 2;
      		//$this->renderToHolder('category/chooseNewCategory.phtml');
      		return;
      	}
        else
        {
        	if($type != 'general') {
        		$this->m->setTables($type);
        	}
        	$this->viewParams['mode'] = 'new';
        	$this->viewParams['form'] = new category_Form_Category();
//        	$this->viewParams['form']->cluBuild(array('type'=>$type, 'view'=>$this->view, 'formName' => 'new'));
        	
        	$actionUrl = $this->view->hvnUrl(array('module' => 'category', 'action'=>'new'), 'nocontroller');
        	$this->viewParams['form']->cluBuild(array('action' => 'new', 'action_url' => $actionUrl, 
        												  'type'=>$type, 'formName' => 'new',
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));

    		$this->viewParams['type'] = $type;
    		$data = $this->_request->getParams();
    		if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
    		{
    			$db = $this->db;
		        $db->beginTransaction(); //TODO: to be moved to Model in v2
	          
		        try
		        {
		        	$data['article_title'] 		= $data['title'];
	            	$data['article_body']  		= $data['description'];
	            	$data['article_language'] 	= $this->_request->getParam('language');
	            	$data['article_module'] 	= "category";
	            	$data['article_status'] 	= isset($data['status']) ? $data['status'] :
	            		Zend_Registry::get('configuration')->general->defaultNodeStatus;
	            	if (!$this->mArticle->insertRaw($data,false))
	            	if (!$this->mArticle->insertRaw($data,array('do_validate' => false)))
	                {
	                	$this->view->errorMessage = t(503);
	                }
	                $article_id = $db->lastInsertId();
	            	$data['article_id'] = $article_id;
			        if($article_id != 0)
	                {
			            try
				    	{
				    	   	$categoryId = $this->m->insertRaw($data,array('do_validate' => false));
				    	}
				    	catch (Exception $e) 
				    	{
				    	    $this->viewParams['errorMessage'] = t(214);
				    		$this->mArticle->deleteByPrimary(array($article_id), false);
				    	}
	                }
	                $db->commit();
		        }
	    		catch (Exception $e)
	            {
	                $db->rollBack();
//	                die($e->getMessage());
	                $this->viewParams['errorMessage'] .= "<br/>" . t(69);
	            } 
                //forward to avoid refreshing
                //$this->_forward("success", 'master' , 'category', array('lastInsertId' => $article_id, 'lang' => 'en' ) );
                $this->_helper->redirector->gotoUrl($this->view->hvnUrl(array(
                														'controller' => 'category',
                														'action' => 'success'			
                														),
                													 'nocontroller')); 
                return;
    		}
	        else if ($this->_request->isPost() )
	        {
	        	$this->viewParams['errorMessage'] = t(1);
	        }
        }
	}
	
	public function viewAction()
    {
    	//check user rights
    	$sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
    	$categoryId = $this->_request->getParam("id");
    	$type = $this->_request->getParam("type");
        if($type != 'general') 
        		$this->m->setTables($type);

        if (!$c = $this->m->findByPrimary($categoryId))
        {
            $this->viewParams['errorMessage'] = __('Cannot find the requested category');
            $this->renderError(null,t(504));
        	return;
        }
       	$this->viewParams['category'] = $c;
       	$this->viewParams['type'] = $type;
       	//$this->renderToHolder( 'category/view.phtml');  
    }
    
    public function editAction()
    {	
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
    	$id = $this->_request->getParam("id");
        $type = $this->_request->getParam("type");
    	$this->viewParams['id'] = $id;
        $this->viewParams['type'] = $type;
        $this->viewParams['mode'] = 'edit';
        
        if($type != 'general') 
    		$this->m->setTables($type);
//        die_a($this->_request->getParams());		
    	if (!$c = $this->m->findByPrimary($id))
        {               
            $this->renderError(null,__('Cannot find the requested category'));
        	return;
        }
        $this->viewParams['article_id'] = $c->article_id;
//        die($this->viewParams['article_id']);
        
        //everything's fine. Continue editing
        $this->viewParams['form'] = new category_Form_Category();
//        $this->viewParams['form']->cluBuild(array('type'=>$type, 'view' => $this->view, 'formName' => 'edit'));
        
        $actionUrl = $this->view->hvnUrl(array('module' => 'category', 'action'=>'edit'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'edit', 'action_url' => $actionUrl, 
        												  'type'=>$type, 'formName' => 'edit',
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        	
        //populate the data from DB
		if (!$this->_request->isPost())
		{
            $formData = $c->toArray();
    		$formData['pid'] = $this->m->findParentId($id);
			$this->viewParams['form']->populate($formData);
		}
		
        else if ($this->viewParams['form']->isValid($_POST))
        {
        	$data = $this->_request->getParams();
        	$articleData = array();
        	$articleData['article_title'] = $data['title'];
            $articleData['article_body'] = $data['description'];
        	$article_id = $data['article_id'];
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,array('do_validate' => false))))
            {
            	//$this->viewParams['errorMessage'] = t(503);
            	$this->renderError(null,t(503));
        		return;
            	
            }
            if ($this->m->saveRaw($c, $this->viewParams['form']->getValues(), $id, false))
            {
                $this->viewParams['operation'] = __("update category");
                //$this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->viewParams['errorMessage'] = __("Could not update category to DB");
        }
        else 
        	$this->viewParams['errorMessage'] = __("Input is not valid");
    }

    public function deleteAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
        
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->viewParams['errorMessage'] = __('No article id specified');
    		$this->renderError(null,t(504));
        	return;
        }
        $type = $this->_request->getParam("type");
        if($type != 'general') 
        		$this->m->setTables($type);
        
        if ($this->m->updateTree($id, -1))
        {
            $this->viewParams['operation'] = __("Delete category");
            //$this->renderToHolder( 'common/success.phtml');
        }
		else
		{   
			$this->viewParams['errorMessage'] = __('Could not delete from DB');
            $this->renderError(null,t(504));
        	return;
		}   
    }
    
	public function searchAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
		//check user rights
        if (strpos ($sess->userPermissions, 'administer everything') === false)
        {
        	$this->renderError(null,t(68));
        	return;
        }
//    	die();
        
//    	die();
      	if(!$type = $this->_request->getParam('type'))
      	{
      		$this->presenceIdentifier = 2;
      		//$this->renderToHolder('category/chooseCategory.phtml');
      		return;
      	}
        else
        {
        	if($type != 'general') {
        		$this->m->setTables($type);
        	}
            $this->viewParams['form'] = new category_Form_Search();
//        	$this->viewParams['form']->cluBuild(array('type'=>$type, 'view' => $this->view));
            
        	$actionUrl = $this->view->hvnUrl(array('module' => 'category', 'action'=>'search'), 'nocontroller');
        	$this->viewParams['form']->cluBuild(array('action' => 'search', 'action_url' => $actionUrl, 
        												  'type'=>$type, 'formName' => 'edit',
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        	
            //TODO: pass type to category_Form_Search so that mCategory can search 
            //the right table
            //wtf????
        	
        	$this->viewParams['type'] = $type;
			if($this->_request->isPost() && $this->viewParams['form']->isValid($_POST))
    	    	if($categoryList = $this->m->search($this->_request->getParams()))
        		{
      				$this->viewParams['categoryList'] = $categoryList;//list of found categories
      				$this->viewParams['type'] = $type;
    	            //$this->renderToHolder('category/list.phtml',false, null, 4,2); 
            	}
            //$this->renderToHolder('category/search.phtml',false, null, 4,1); //search box 
        }
    }
    
	public function successAction()
    {
         $this->viewParams['categoryId'] =  $this->_request->getParam("lastInsertId");
//         die('success');
         //$this->renderToHolder( 'common/success.phtml');  
    }
}
?>
